﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
namespace NetCoreCMS.Web.Areas.Admin.Controllers.Article
{
    public class Category_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Article/category_edit.cshtml";
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        protected int channel_id;
        public IArticle_categoryService _article_category { get; set; }
        public IArticle_specService _article_spec { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            this.channel_id = CMSRequest.GetQueryInt("channel_id", filterContext.HttpContext);
            ChkAdminLevel("article_" + this.channel_id + "_category", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ActionResult result = View(EDIT_RESULT_VIEW);
            string _action = Request.Query["action"];
            
            int.TryParse(Request.Query["id"],out this.id);

            if (!string.IsNullOrEmpty(_action) && _action == CMSEnums.ActionEnum.Edit.ToString())
            {
                this.action = CMSEnums.ActionEnum.Edit.ToString();//修改类型
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = result;
                    return;
                }
                if (!_article_category.Exists(this.id))
                {
                    JscriptMsg("类别不存在或已被删除！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
            ViewBag.ChannelId = this.channel_id.ToString();
            ViewBag.Id = this.id.ToString();
            ViewBag.Action = this.action;
        }
        // GET: /admin/Category_Edit/

        public ActionResult Index()
        {
            TreeBind(); //绑定类别
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                Article_category model = new Article_category();
                model.parent_id = this.id;
                model.sort_id = 99;
                ViewData["model"] = model;
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave(string txtContent)
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("article_" + this.channel_id + "_category", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id, txtContent))
                {

                    JscriptMsg("保存过程中发生错误！", "");
                    return result;
                }
                ViewBag.ClientScript = JscriptMsg("修改类别成功！", "../category_list/index?channel_id=" + channel_id);
            }
            else //添加
            {
                ChkAdminLevel("article_" + this.channel_id + "_category", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd(txtContent))
                {
                    JscriptMsg("保存过程中发生错误！", "");
                    return result;
                }
                JscriptMsg("添加类别成功！", "../category_list/index?channel_id=" + channel_id);
            }
            return result;
        }

        #region 绑定类别=================================
        private void TreeBind()
        {
            var dt = _article_category.GetList(0,this.channel_id);
            List<SelectListItem> parentList = new List<SelectListItem>() {
              new SelectListItem(){ Text="无父级类别", Value="0" }
           };
            foreach (Article_category dr in dt)
            {
                string Id = dr.id.ToString();
                int ClassLayer = dr.class_layer;
                string Title = dr.title;

                if (ClassLayer == 1)
                {
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            ViewData["selectListItems"] = parentList;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            Article_category model = _article_category.GetModel(_id);
            ViewData["model"] = model;
            //绑定类别规格
            var list = _article_spec.GetCategorySpecList(model.id);
            ViewData["list"] = list;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd(string txtContent)
        {
            try
            {
                Article_category model = new Article_category();
                model.title = Request.Form["txtTitle"].FirstOrDefault().Trim();
                model.parent_id = int.Parse(Request.Form["ddlParentId"]);
                model.sort_id = int.Parse(Request.Form["txtSortId"].FirstOrDefault().Trim());
                model.seo_title = Request.Form["txtSeoTitle"];
                model.seo_keywords = Request.Form["txtSeoKeywords"];
                model.seo_description = Request.Form["txtSeoDescription."];
                model.link_url = Request.Form["txtLinkUrl"].FirstOrDefault().Trim();
                model.img_url = Request.Form["txtImgUrl"].FirstOrDefault().Trim();
                model.content = txtContent;
                model.channel_id = this.channel_id;
                #region 保存规格====================
                string[] specIdArr = Request.Form["hide_spec_id"];
                if (specIdArr != null && specIdArr.Length > 0)
                {
                    List<Article_category_spec> ls = new List<Article_category_spec>();
                    for (int i = 0; i < specIdArr.Length; i++)
                    {
                        int specId = Utils.StrToInt(specIdArr[i], 0);
                        ls.Add(new Article_category_spec { spec_id = specId });
                    }
                    model.category_specs = ls;
                }
                #endregion
                if (_article_category.Add(model) > 0)
                {
                    AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加栏目分类:" + model.title); //记录日志
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id, string txtContent)
        {
            try
            {
                Article_category model = _article_category.GetModel(_id);

                int parentId = int.Parse(Request.Form["ddlParentId"]);
                model.title = Request.Form["txtTitle"].FirstOrDefault().Trim();
                //如果选择的父ID不是自己,则更改
                if (parentId != model.id)
                {
                    model.parent_id = parentId;
                }
                model.sort_id = int.Parse(Request.Form["txtSortId"].FirstOrDefault().Trim());
                model.seo_title = Request.Form["txtSeoTitle"];
                model.seo_keywords = Request.Form["txtSeoKeywords"];
                model.seo_description = Request.Form["txtSeoDescription"];
                model.link_url = Request.Form["txtLinkUrl"].FirstOrDefault().Trim();
                model.img_url = Request.Form["txtImgUrl"].FirstOrDefault().Trim();
                model.content = txtContent;
                #region 保存规格====================
                if (model.category_specs != null)
                {
                    model.category_specs.Clear();
                }
                string[] specIdArr = Request.Form["hide_spec_id"];
                if (specIdArr != null && specIdArr.Length > 0)
                {
                    List<Article_category_spec> ls = new List<Article_category_spec>();
                    for (int i = 0; i < specIdArr.Length; i++)
                    {
                        int specId = Utils.StrToInt(specIdArr[i], 0);
                        ls.Add(new Article_category_spec { category_id = model.id, spec_id = specId });
                    }
                    model.category_specs = ls;
                }
                #endregion
                if (_article_category.Update(model))
                {
                    AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改栏目分类:" + model.title); //记录日志
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion
    }
}
